import { ref,reactive } from "vue"
import { request } from '../utils/request'
import { defineStore } from "pinia"
import { setToken, getToken,removeToken } from "../utils/cookies"
import {routes} from '../router/index'
import { createPinia } from "pinia"

const store = createPinia()


/** 登录并返回 Token */

interface LoginRequestData {
    /** admin 或 editor */
    username: "admin" | "editor"
    /** 密码 */
    password: string
    /** 验证码 */
    code: string,
    uuid: String
}
/** 获取用户详情 */
function getUserInfoApi() {
    return request({
        url: "api/getInfo",
        method: "get"
    })
}
export const useUserStore = defineStore('user', () => {
    const token = ref<string>(getToken() || "")
    const roles = ref<string[]>([])
    const username = ref<string>("")
    const user = reactive( {value:{}})
    const islogin = ref(false)

    /** 登录 */
    // const login = async ({ username, password, code, uuid }: LoginRequestData) => {
    //     const { data } = await loginApi({ username, password, code })
    //     setToken(data.token)
    //     token.value = data.token
    //     islogin.value=true
    //     getInfo()
    // }
    /** 获取用户详情 */
    const getInfo = async () => {
        const resp = await getUserInfoApi()
        username.value = resp.user.nickname
        // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
        roles.value = resp.roles?.length > 0 ? resp.roles : routes
        islogin.value = true
        user.value = resp.user
    }
    /** 模拟角色变化 */
    const changeRoles = async (role: string) => {
        const newToken = "token-" + role
        token.value = newToken
        setToken(newToken)
        // 用刷新页面代替重新登录
        window.location.reload()
    }
    /** 登出 */
    const logout = () => {
        removeToken()
        token.value = ""
        roles.value = []
        islogin.value=false
    }
    /** 重置 Token */
    const resetToken = () => {
        removeToken()
        token.value = ""
        roles.value = []
        
    }
    const getlogin = (state) => {

        if (getToken()) {
            
            getInfo()
        } else {
            islogin.value = false
        }

        return islogin.value
    }
    return { token, roles, username,user, logout , getInfo, changeRoles,  resetToken,
        getlogin
     }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
    return useUserStore(store)
}

 
export const useCounterStore = defineStore('counter', {
    state: () => ({ islogin: false }),
    getters: {
        getlogin: (state) => state.islogin,
    },
    actions: {
        dologin() {
            this.islogin = true
        },
        dologout() {
            this.islogin = false
        },
    },
})